package com.huifanedu.approval.listener;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huifanedu.approval.constant.FlowableConstant;
import com.huifanedu.approval.entity.ApprovalFlowTaskcfg;
import com.huifanedu.approval.entity.ApprovalFormData;
import com.huifanedu.approval.entity.ApprovalInfo;
import com.huifanedu.approval.notify.MessageProduct;
import com.huifanedu.approval.notify.model.UserTaskCreateRecord;
import com.huifanedu.approval.service.ApprovalFlowTaskcfgService;
import com.huifanedu.approval.service.ApprovalFormDataService;
import com.huifanedu.approval.service.ApprovalInfoService;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.RuntimeService;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.Date;
import java.util.List;

/**
 * <b>功能名：任务节点前置监听处理类</b><br>
 * <b>说明：TaskBeforeListener</b><br>
 * <b>著作权：</b> Copyright (C) 2020 HUIFANEDU CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2021-3-10 jiabingbing
 */
public class TaskBeforeListener implements FlowableEventListener {

    private static final Logger log = LoggerFactory.getLogger(TaskBeforeListener.class);
    @Autowired
    private ApprovalFlowTaskcfgService approvalFlowTaskcfgService;

    @Autowired
    private MessageProduct messageProduct;

    @Autowired
    @Lazy
    private RuntimeService runtimeService;

    @Autowired
    @Lazy
    private ApprovalFormDataService approvalFormDataService;
    @Autowired
    @Lazy
    private ApprovalInfoService approvalInfoService;

    @Override
    public void onEvent(FlowableEvent event) {
        TaskEntity taskEntity = (TaskEntity) ((FlowableEntityEventImpl) event).getEntity();
        System.out.println("-----------------------------------------------设置任务节点过期时间------------------------------------------------------");
        List<ApprovalFlowTaskcfg> taskConfig = approvalFlowTaskcfgService.list(Wrappers.<ApprovalFlowTaskcfg>lambdaQuery()
                .eq(ApprovalFlowTaskcfg::getAftTaskId, taskEntity.getTaskDefinitionKey())
                .eq(ApprovalFlowTaskcfg::getAftProcDefId, taskEntity.getProcessDefinitionId()));
        Date createTime = taskEntity.getCreateTime() != null ? taskEntity.getCreateTime() : new Date();
        //默认永不过期
        long taskOverTime = FlowableConstant.TASK_MAX_EXPIRE_TIME;
        if (taskConfig != null && taskConfig.size() > 0
                && taskConfig.get(0).getAftApprovalTime() != null
                && taskConfig.get(0).getAftApprovalTime() > 0) {
            taskOverTime = createTime.getTime() + taskConfig.get(0).getAftApprovalTime() * 60 * 60 * 1000L;
        }
        //设置当前任务节点过期时间
        taskEntity.setVariable(FlowableConstant.TASK_VARIABLE_OVER_TIME, taskOverTime);
        //调用消息推送任务
        try {
            String formDataId = runtimeService.getVariable(taskEntity.getProcessInstanceId(), FlowableConstant.BUSINESS_KEY, String.class);
            ApprovalFormData formData = approvalFormDataService.getOne(Wrappers.<ApprovalFormData>lambdaQuery()
                    .eq(ApprovalFormData::getAfdId, formDataId));
            if (formData != null) {
                UserTaskCreateRecord record = new UserTaskCreateRecord();
                ApprovalInfo approvalInfo = approvalInfoService.getOne(Wrappers.<ApprovalInfo>lambdaQuery()
                        .eq(ApprovalInfo::getAiId, formData.getAfdApprovalId()));
                record.setTaskId(taskEntity.getId());
                record.setTaskName(taskEntity.getName());
                record.setApprovalCatalogId(approvalInfo.getAiCtalogId());
                record.setApprovalInfoName(approvalInfo.getAiName());
                record.setApprovalInfoId(approvalInfo.getAiId());
                record.setApprovalName(formData.getAfdTitle());
                record.setApprovalOrgId(formData.getAfdOrgId());
                record.setApprovalOrgName(formData.getAfdOrgName());
                record.setApprovalUserId(formData.getAfdUserId());
                record.setApprovalUserName(formData.getAfdUserName());
                record.setCreateTime(taskEntity.getCreateTime());
                record.setTaskAssignee(taskEntity.getAssignee());
                if (taskOverTime != FlowableConstant.TASK_MAX_EXPIRE_TIME) {
                    record.setExpireTime(new Date(taskOverTime));
                }
                record.setProcessInstanceId(taskEntity.getProcessInstanceId());
                messageProduct.sendUserTaskCreateMsg(record);
            }

        } catch (Exception e) {
            log.info("任务已签收但是发送消息异常", e);
        }
    }


    /**
     * 该isFailOnException()方法确定onEvent(..)方法在调度事件时抛出异常时的行为。
     * 当false返回，异常被忽略。当true返回，异常不会被忽略
     *
     * @return
     */
    @Override
    public boolean isFailOnException() {
        return true;
    }

    /**
     * 该isFireOnTransactionLifecycleEvent()方法确定此事件侦听器是在事件发生时立即触发,还是由getOnTransaction()方法确定的事务生命周期事件触发。
     * 支持的事务生命周期事件的值是：COMMITTED，ROLLED_BACK，COMMITTING，ROLLINGBACK。
     *
     * @return
     */
    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}